package com.totoro.config;

import com.totoro.pojo.User;
import com.totoro.utils.Base64EncryptionUtil;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author TOTORO
 * @date 2021/8/15 23:14
 */
public class LoginInterceptor implements HandlerInterceptor {

    Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        //执行完毕，返回前拦截
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        //处理过程中执行拦截
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        HttpSession session = request.getSession();
        logger.info("拦截页面："+request.getRequestURI()+"?"+request.getQueryString());
        User user = (User) session.getAttribute("user");
        //在拦截点执行前拦截，如果返回true则不执行拦截点后的操作（拦截成功）
        //返回false则不执行拦截
        if(null == user) {
            // 获取拦截登录之前的页面url，实现登录后还是返回原页面
            String beforeUrl = request.getRequestURI()+"?"+request.getQueryString();
            //登录失败，跳转到登录页
            response.sendRedirect("/login.htm?ttr="+new String(Base64EncryptionUtil.base64Encrypt(beforeUrl)));
            return false;
        }else{
            //登陆成功，不拦截
            return true;
        }
    }

}
